package com.web.util;

import com.alibaba.fastjson.JSONObject;
import com.ceph.rados.exceptions.ErrorCode;
import com.ceph.rbd.RbdException;
import com.web.exception.CephWebException;
import com.web.wrapper.RbdParameter;
import com.web.wrapper.hood.CephRBDAccessor;
import com.web.wrapper.hood.CephRados;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public class util
{
	public static int SUCCESS = 0;
	public static int FAIL = 1;

	public static void main(String[] args) {
		RbdParameter pp = new RbdParameter("rbd", "foo", "nature01");
	}

	public static <T> T fromJson(String str, Class<T> clazz) {
		if (null == str)
			return null;
		try {
			return JSONObject.parseObject(str, clazz);
		}
		catch (Exception e) {
		}
		return null;
	}

	public static void setRados(ServletContext sc, CephRBDAccessor rbd) {
		if (null == rbd.getRados()) {
			CephRados rados = (CephRados)WebApplicationContextUtils.getRequiredWebApplicationContext(sc).getBean(CephRados.class);
			rbd.setRados(rados);
		}
	}

	public static String cephErrMsg(Exception e) {
		String cephErrMsg = "";
		if ((e instanceof RbdException)) {
			int retValue = ((RbdException)e).getReturnValue();
			cephErrMsg = ErrorCode.getErrorMessage(retValue);
		}
		return cephErrMsg;
	}

	public static void nullCheck(Object r) throws Exception {
		if (null == r)
			throw new NullPointerException("No rados defined");
	}

	public static String getParam(HttpServletRequest request, String key) {
		if (null != request.getParameter(key)) {
			return request.getParameter(key);
		}
		return "";
	}

	public static Long getLongParam(HttpServletRequest request, String key) {
		String v = request.getParameter(key);
		if (null == v)
			v = "0";
		try {
			return Long.valueOf(v); } catch (NumberFormatException e) {
		}
		return Long.valueOf(0L);
	}

	public static String getParamIgrCase(HttpServletRequest request, String key) {
		if (key == null) {
			return "";
		}
		if (null != request.getParameter(key))
			return request.getParameter(key);
		if (null != request.getParameter(key.toLowerCase())) {
			return request.getParameter(key.toLowerCase());
		}
		return "";
	}

	public static JSONObject formatReturn(int code, String message) {
		JSONObject result = new JSONObject();
		result.put("code", code == FAIL ? "fail" : "success");
		result.put("msg", message);
		return result;
	}
	
	public static JSONObject formatReturn(int code, String message, Object data) {
		JSONObject result = new JSONObject();
		result.put("code", code == FAIL ? "fail" : "success");
		result.put("msg", message);
		result.put("data", data);
		return result;
	}
	

}